<template>
  <div class="p-2">
    <a-card style="width: 100%">
      <a-spin :spinning="confirmLoading" :tip="confirmTip">
        <a-form ref="formRef" class="antd-modal-form" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-row>
            <a-col :span="12">
              <a-form-item label="提货时间" v-bind="validateInfos.deliveryTime">
                <a-date-picker placeholder="请选择提货时间" v-model:value="formData.deliveryTime"
                               showTime value-format="YYYY-MM-DD HH:mm:ss" style="width: 100%"
                               :disabled="disabled"/>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="预计送达时间" v-bind="validateInfos.estArrivalTime">
                <a-date-picker placeholder="请选择预计送达时间"
                               v-model:value="formData.estArrivalTime" showTime
                               value-format="YYYY-MM-DD HH:mm:ss" style="width: 100%"
                               :disabled="disabled"/>
              </a-form-item>
            </a-col>
          </a-row>
          <a-row justify="space-around">
            <a-col :span="12">
              <a-card size="small" title="发货方" :bordered="false"
                      :headStyle="{background:'#1890ff',color:'white'}">
                <a-row>
                  <a-col :span="12">
                    <a-form-item label="姓名" v-bind="validateInfos.shipperName">
                      <!--                      <a-input v-model:value="formData.shipperName" placeholder="请输入发货人姓名"
                                                     :disabled="disabled"></a-input>-->
                      <AutoComplete
                        v-model:value="formData.shipperName"
                        style="width: 16vw"
                        placeholder="请输入发货人姓名"
                        :options="bothSides"
                        :allowClear="true"
                        @focus="()=>handleSearchBoth({name:`*${formData.shipperName}*`,sidesType:'1'})"
                        @search="(name: string)=>handleSearchBoth({name:`*${name}*`,sidesType:'1'})"
                      >
                        <template #option="item">
                          <a-tooltip placement="rightTop">
                            <template #title>{{ item.name }} {{ item.idNum }} {{ item.phone }}
                              {{ item.areaName }} {{ item.detailAddr }}
                            </template>
                            <span @click="selectShipper(item)">{{ item.name }}     {{
                                item.idNum
                              }}</span>
                          </a-tooltip>

                        </template>
                      </AutoComplete>
                    </a-form-item>
                  </a-col>
                  <a-col :span="12">
                    <a-form-item label="电话" v-bind="validateInfos.shipperPhone">
                      <a-input v-model:value="formData.shipperPhone" placeholder="请输入发货人电话"
                               :disabled="disabled"></a-input>
                    </a-form-item>
                  </a-col>
                </a-row>
                <a-col :span="24">
                  <a-form-item label="证件号" v-bind="validateInfos.shipperIdNum">
                    <a-input v-model:value="formData.shipperIdNum" placeholder="请输入发货人证件号"
                             :disabled="disabled"></a-input>
                  </a-form-item>
                </a-col>
                <a-col :span="24">
                  <a-form-item label="地区" v-bind="validateInfos.shipperAreaCode">
                    <j-area-select v-model:value="formData.shipperAreaCode"
                                   placeholder="请输入发货人地区编码" :disabled="disabled"
                                   @change="(code)=>{if(code) formData.shipperAreaName=getTextByCode(code)}"
                                   style="width:100%"/>
                  </a-form-item>
                </a-col>
                <a-col :span="24">
                  <a-form-item label="详细地址" v-bind="validateInfos.shipperDetailAddr">
                    <a-textarea v-model:value="formData.shipperDetailAddr" :rows="2"
                                placeholder="请输入发货人详细地址，城镇、乡村、街道、门牌号码、屋邨、大厦，如：阜通东大街6号"
                                :disabled="disabled"/>
                  </a-form-item>
                </a-col>
              </a-card>
            </a-col>

            <a-col :span="12">
              <a-card size="small" title="收货方" :bordered="false"
                      :headStyle="{background:'#1890ff',color:'white'}">
                <a-row>
                  <a-col :span="12">
                    <a-form-item label="姓名" v-bind="validateInfos.consignerName">

                      <AutoComplete
                        v-model:value="formData.consignerName"
                        style="width: 16vw"
                        placeholder="请输入收货人姓名"
                        :options="bothSides"
                        :allowClear="true"
                        @focus="()=>handleSearchBoth({name:`*${formData.consignerName}*`,sidesType:'2'})"
                        @search="(name: string)=>handleSearchBoth({name:`*${name}*`,sidesType:'2'})"
                      >
                        <template #option="item">
                          <a-tooltip placement="rightTop">
                            <template #title>{{ item.name }} {{ item.idNum }} {{ item.phone }}
                              {{ item.areaName }} {{ item.detailAddr }}
                            </template>
                            <span @click="selectConsigner(item)">{{ item.name }}     {{
                                item.idNum
                              }}</span>
                          </a-tooltip>

                        </template>
                      </AutoComplete>
                    </a-form-item>
                  </a-col>
                  <a-col :span="12">
                    <a-form-item label="电话" v-bind="validateInfos.consignerPhone">
                      <a-input v-model:value="formData.consignerPhone"
                               placeholder="请输入收货人电话"
                               :disabled="disabled"></a-input>
                    </a-form-item>
                  </a-col>
                </a-row>


                <a-col :span="24">
                  <a-form-item label="证件号" v-bind="validateInfos.consignerIdNum">
                    <a-input v-model:value="formData.consignerIdNum"
                             placeholder="请输入收件人证件号"
                             :disabled="disabled"></a-input>
                  </a-form-item>
                </a-col>
                <a-col :span="24">
                  <a-form-item label="地区" v-bind="validateInfos.consignerAreaCode">
                    <j-area-select v-model:value="formData.consignerAreaCode"
                                   @change="(code)=>{if(code) formData.consignerAreaName=getTextByCode(code)}"
                                   placeholder="请输入收货人地区编码" :disabled="disabled"/>
                  </a-form-item>
                </a-col>

                <a-col :span="24">
                  <a-form-item label="详细地址" v-bind="validateInfos.consignerDetailAddr">
                    <a-textarea v-model:value="formData.consignerDetailAddr" :rows="2"
                                placeholder="请输入收货人详细地址，城镇、乡村、街道、门牌号码、屋邨、大厦，如：阜通东大街6号"
                                :disabled="disabled"/>
                  </a-form-item>
                </a-col>


              </a-card>

            </a-col>
          </a-row>
          <a-card size="small" title="货物信息" :bordered="false"
                  :headStyle="{background:'#1890ff',color:'white'}">
            <a-row>
              <a-col :span="4">
                <a-form-item label="名称" v-bind="validateInfos.cargoName">
                  <a-input v-model:value="formData.cargoName" placeholder="请输入货物名称"
                           :disabled="disabled"></a-input>
                </a-form-item>
              </a-col>
              <a-col :span="4">
                <a-form-item label="件数" v-bind="validateInfos.cargoPieces">
                  <a-input-number v-model:value="formData.cargoPieces" placeholder="请输入货物件数"
                                  :min="0"
                                  style="width: 100%" :disabled="disabled"/>
                </a-form-item>
              </a-col>
              <a-col :span="4">
                <a-form-item label="重量" v-bind="validateInfos.cargoWeight">
                  <a-input-number v-model:value="formData.cargoWeight" placeholder="请输入货物重量"
                                  :min="0"

                                  style="width: 100%" :disabled="disabled"/>
                </a-form-item>
              </a-col>
              <a-col :span="4">
                <a-form-item label="体积" v-bind="validateInfos.cargoVolume">
                  <a-input-number v-model:value="formData.cargoVolume" placeholder="请输入货物体积"
                                  :min="0"

                                  style="width: 100%" :disabled="disabled"/>
                </a-form-item>
              </a-col>
              <a-col :span="4">
                <a-form-item label="货值" v-bind="validateInfos.cargoPrice">
                  <a-input-number v-model:value="formData.cargoPrice" placeholder="请输入货物价值"
                                  :min="0"

                                  style="width: 100%" :disabled="disabled"/>
                </a-form-item>
              </a-col>
              <a-col :span="4">
                <a-form-item label="备注" v-bind="validateInfos.cargoRemark">
                  <a-input v-model:value="formData.cargoRemark" placeholder="请输入货物备注"
                           :disabled="disabled"></a-input>
                </a-form-item>
              </a-col>
            </a-row>
          </a-card>
          <a-card size="small" title="其他" :bordered="false"
                  :headStyle="{background:'#1890ff',color:'white'}">
            <a-row>
              <a-col :span="12">
                <a-form-item label="代收款" v-bind="validateInfos.invoicingFee">
                  <a-input-number v-model:value="formData.invoicingFee" placeholder="请输入代收款"
                                  :min="0"
                                  style="width: 100%" :disabled="disabled"/>
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="支付方式" v-bind="validateInfos.invoicingPayMode">
                  <j-checkbox type="checkbox" v-model:value="formData.invoicingPayMode"
                              dictCode="pay_mode" placeholder="请选择代收款支付方式"
                              :disabled="disabled"/>
                </a-form-item>
              </a-col>
            </a-row>
          </a-card>


          <a-card size="small" title="承运人信息" :bordered="false"
                  :headStyle="{background:'#1890ff',color:'white'}">
            <a-row>
              <a-col :span="12">
                <a-form-item label="司机运费" v-bind="validateInfos.driverFreightFee">
                  <a-input-number v-model:value="formData.driverFreightFee"
                                  placeholder="请输入司机运费" style="width: 100%"
                                  :min="0.01"

                                  :disabled="disabled"/>
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="是否指派司机" v-bind="validateInfos.izAssignDriver">
                  <a-space>
                    <j-switch v-model:value="formData.izAssignDriver" :options="[1,0]"
                              :disabled="disabled"></j-switch>
                    <span
                      style="color: grey;font-size: 0.9em"> 如果不指派司机，订单将发布到订单池，司机可以进行抢单接单</span>
                  </a-space>
                </a-form-item>
              </a-col>
            </a-row>
            <div v-if="formData.izAssignDriver == 1">
              <a-row>
                <a-col :span="8">
                  <a-form-item label="车牌号" v-bind="validateInfos.driverVehicleNo">
                    <!--                    <a-input v-model:value="formData.driverVehicleNo" placeholder="请输入司机车牌号"
                                                 :disabled="disabled"></a-input>-->
                    <AutoComplete
                      v-model:value="formData.driverVehicleNo"
                      style="width: 16vw"
                      placeholder="请输入车牌号"
                      :options="drivers"
                      :allowClear="true"
                      @focus="()=>handleSearchDriver({driverVehicleNo:`*${formData.driverVehicleNo}*`})"
                      @search="(name: string)=>handleSearchDriver({driverVehicleNo:`*${name}*`})"
                    >
                      <template #option="item">
                        <a-tooltip placement="rightTop">
                          <template #title>

                            <div>
                              {{ item.driverVehicleNo }} {{ item.driverName }} {{
                                item.driverPhone
                              }}
                            </div>
                            <div> {{ item.driverBankName }}</div>
                            <div> {{ item.driverBankCardNo }}</div>

                          </template>
                          <span @click="selectDriver(item)">{{
                              item.driverVehicleNo
                            }} {{ item.driverName }} {{ item.driverPhone }} </span>
                        </a-tooltip>

                      </template>
                    </AutoComplete>

                  </a-form-item>
                </a-col>
                <a-col :span="8">
                  <a-form-item label="电话" v-bind="validateInfos.driverPhone">
                    <a-input v-model:value="formData.driverPhone" placeholder="请输入司机电话"
                             :disabled="true"></a-input>
                  </a-form-item>
                </a-col>
                <a-col :span="8">
                  <a-form-item label="姓名" v-bind="validateInfos.driverName">
                    <a-input v-model:value="formData.driverName" placeholder="请输入司机姓名"
                             :disabled="true"></a-input>
                  </a-form-item>
                </a-col>
              </a-row>
              <a-row>
                <a-col :span="8">
                  <a-form-item label="银行开户名" v-bind="validateInfos.driverBankHolder">
                    <a-input v-model:value="formData.driverBankHolder"
                             placeholder="请输入司机银行开户名" :disabled="true"></a-input>
                  </a-form-item>
                </a-col>
                <a-col :span="8">
                  <a-form-item label="银行卡号" v-bind="validateInfos.driverBankCardNo">
                    <a-input v-model:value="formData.driverBankCardNo"
                             placeholder="请输入司机银行卡号"
                             :disabled="true"></a-input>
                  </a-form-item>
                </a-col>
                <a-col :span="8">
                  <a-form-item label="开户银行" v-bind="validateInfos.driverBankName">
                    <a-input v-model:value="formData.driverBankName"
                             placeholder="请输入司机开户银行"
                             :disabled="true"></a-input>
                  </a-form-item>
                </a-col>
              </a-row>
            </div>
          </a-card>
          <a-row justify="center" style="margin: 5vh 0">
            <a-space>
              <a-button type="primary" @click="submitForm">下单</a-button>
              <a-button @click="saveDraft">保存草稿箱</a-button>
              <a-popconfirm title="是否确认清空？" @confirm="reset" ok-text="确认"
                            cancel-text="取消">
                <a-button>清空</a-button>
              </a-popconfirm>

            </a-space>
          </a-row>
        </a-form>
      </a-spin>
    </a-card>
  </div>
</template>

<script lang="ts" name="shipOrder-wlhyWaybill" setup>

import {ref, reactive, defineExpose, nextTick, defineProps, computed, onMounted} from 'vue';
import {defHttp} from '/@/utils/http/axios';
import {useMessage} from '/@/hooks/web/useMessage';
import JDictSelectTag from '/@/components/Form/src/jeecg/components/JDictSelectTag.vue';
import JSwitch from '/@/components/Form/src/jeecg/components/JSwitch.vue';
import JSearchSelect from '/@/components/Form/src/jeecg/components/JSearchSelect.vue';
import JAreaSelect from '/@/components/Form/src/jeecg/components/JAreaSelect.vue';
import JCheckbox from "/@/components/Form/src/jeecg/components/JCheckbox.vue";
import {getValueType} from '/@/utils';
import {Form} from 'ant-design-vue';
import {downOrder} from "@/views/waybill/WlhyWaybill.api";
import {saveOrUpdate as draftSaveOrUpdate} from "@/views/waybill/WlhyWaybillDraft.api";
import {getTextByCode} from "@/components/Form/src/utils/areaDataUtil";
import {AutoComplete} from "ant-design-vue/lib";
import {useDebounceFn} from "@vueuse/core";
import useInfo from "@/hooks/wlhy/useInfo";
import {list} from "@/views/company/WlhyCompanyBothSides.api";
import {list as driverList} from "@/views/company/WlhyCompanyDriver.api";

const props = defineProps({
  formDisabled: {type: Boolean, default: false},
  formData: {
    type: Object, default: () => {
    }
  },
  formBpm: {type: Boolean, default: true}
});
const {getCompanyInfo} = useInfo();

const companyInfo = reactive({
  id: ''
});
const bothSides = ref<{}[]>([]);
const drivers = ref<{}[]>([]);
;
const formRef = ref();
const useForm = Form.useForm;
const emit = defineEmits(['register', 'ok']);
const formData = reactive<Record<string, any>>({
  id: '',
  userId: '',
  waybillNo: '',
  deliveryTime: '',
  estArrivalTime: '',
  shipperName: '',
  shipperPhone: '',
  shipperIdNum: '',
  shipperAreaCode: '',
  shipperAreaName: '',
  shipperDetailAddr: '',
  shipperLnglat: '',
  consignerName: '',
  consignerPhone: '',
  consignerIdNum: '',
  consignerAreaCode: '',
  consignerAreaName: '',
  consignerDetailAddr: '',
  consignerLnglat: '',
  cargoName: '',
  cargoPieces: undefined,
  cargoWeight: undefined,
  cargoVolume: undefined,
  cargoPrice: undefined,
  cargoRemark: '',
  invoicingFee: undefined,
  invoicingPayMode: '',
  izInvoicingFee: undefined,
  invoicingOrderNum: '',
  invoicingRealPayMode: '',
  driverFreightFee: undefined,
  settleFreightStatus: undefined,
  settleFreightTime: '',
  settleFreightMode: '',
  izAssignDriver: undefined,
  orderTime: '',
  driverUserId: '',
  driverVehicleNo: '',
  driverPhone: '',
  driverName: '',
  driverBankId: '',
  driverBankHolder: '',
  driverBankCardNo: '',
  driverBankName: '',
  scanNum: undefined,
  commentNum: '',
  waybillStatus: '',
  status: '',
});
const {createMessage} = useMessage();
const labelCol = ref<any>({xs: {span: 24}, sm: {span: 5}});
const wrapperCol = ref<any>({xs: {span: 24}, sm: {span: 16}});
const confirmLoading = ref<boolean>(false);
const confirmTip = ref<string>("");
//表单验证
const validatorRules = {
  deliveryTime: [{required: true, message: '请填写提货时间', trigger: 'change'}],
  estArrivalTime: [{required: true, message: '请填写预计送达时间', trigger: 'change'}],
  shipperName: [{required: true, message: '请填写发货人姓名', trigger: 'change'}],
  shipperPhone: [{
    required: true,
    message: '请填写发货人电话',
    trigger: 'change'
  }, {pattern: /^1[3456789]\d{9}$/, message: '发货人电话号码格式有误', trigger: 'change'}],
  shipperIdNum: [{
    required: true,
    message: '请填写发货人证件号',
    trigger: 'change'
  }, {
    pattern: /^[1-9]\d{5}(19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}(\d|X|x)$/,
    message: '发货人证件号格式有误',
    trigger: 'change'
  }],
  shipperAreaCode: [{required: true, message: '请填写发货人地区', trigger: 'change'}],
  shipperDetailAddr: [{required: true, message: '请填写发货人详细地址', trigger: 'change'}],

  consignerName: [{required: true, message: '请填写收货人姓名', trigger: 'change'}],
  consignerPhone: [{
    required: true,
    message: '请填写收货人电话',
    trigger: 'change'
  }, {pattern: /^1[3456789]\d{9}$/, message: '收货人电话号码格式有误', trigger: 'change'}],
  consignerIdNum: [{
    required: true,
    message: '请填写收货人证件号',
    trigger: 'change'
  }, {
    pattern: /^[1-9]\d{5}(19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}(\d|X|x)$/,
    message: '收货人证件号格式有误',
    trigger: 'change'
  }],
  consignerAreaCode: [{required: true, message: '请填写收货人地区', trigger: 'change'}],
  consignerDetailAddr: [{required: true, message: '请填写收货人详细地址', trigger: 'change'}],


  cargoName: [{required: true, message: '请填写货物名称', trigger: 'change'}],
  cargoPieces: [{required: true, message: '请填写货物件数', trigger: 'change'}],
  cargoWeight: [{required: true, message: '请填写货物重量 ', trigger: 'change'}],
  cargoVolume: [{required: true, message: '请填写货物体积', trigger: 'change'}],
  cargoPrice: [{required: true, message: '请填写货物价值', trigger: 'change'}],
  driverFreightFee: [{required: true, message: '请填写司机运费', trigger: 'change'}],
};
const {
  resetFields,
  validate,
  validateInfos
} = useForm(formData, validatorRules, {immediate: false});


// 表单禁用
const disabled = computed(() => {
  /* if(props.formBpm === true){
     if(props.formData.disabled === false){
       return false;
     }else{
       return true;
     }
   }
   return props.formDisabled;*/
  return false;
});


/**
 * 新增
 */
function add() {
  edit({});
}

/**
 * 编辑
 */
function edit(record) {
  nextTick(() => {
    resetFields();
    const tmpData = {};
    Object.keys(formData).forEach((key) => {
      if (record.hasOwnProperty(key)) {
        tmpData[key] = record[key]
      }
    })
    //赋值
    Object.assign(formData, tmpData);
  });
}

/**
 * 清空
 */
const reset = () => {
  resetFields();
}

/**
 * 提交数据
 */
async function submitForm() {
  // 触发表单验证
  await validate();
  confirmLoading.value = true;
  confirmTip.value = "下单中...";
  const isUpdate = ref<boolean>(false);
  //时间格式化
  let model = formData;
  if (model.id) {
    isUpdate.value = true;
  }
  //循环数据
  for (let data in model) {
    //如果该数据是数组并且是字符串类型
    if (model[data] instanceof Array) {
      let valueType = getValueType(formRef.value.getProps, data);
      //如果是字符串类型的需要变成以逗号分割的字符串
      if (valueType === 'string') {
        model[data] = model[data].join(',');
      }
    }
  }
  console.log("model", model)
  await downOrder(model)
    .then((res) => {
      if (res.success) {
        createMessage.success(res.message);
      } else {
        createMessage.warning(res.message);
      }
    })
    .finally(() => {
      confirmLoading.value = false;
      confirmTip.value = "Loading...";

    });
}


/**
 * 提交数据
 */
async function saveDraft() {
  // 触发表单验证
  await validate();
  confirmLoading.value = true;
  confirmTip.value = "存稿中...";
  const isUpdate = ref<boolean>(false);
  //时间格式化
  let model = formData;
  if (model.id) {
    isUpdate.value = true;
  }
  //循环数据
  for (let data in model) {
    //如果该数据是数组并且是字符串类型
    if (model[data] instanceof Array) {
      let valueType = getValueType(formRef.value.getProps, data);
      //如果是字符串类型的需要变成以逗号分割的字符串
      if (valueType === 'string') {
        model[data] = model[data].join(',');
      }
    }
  }
  console.log("model", model)
  await draftSaveOrUpdate(model, false)
    .then((res) => {
      if (res.success) {
        createMessage.success(res.message);
      } else {
        createMessage.warning(res.message);
      }
    })
    .finally(() => {
      confirmLoading.value = false;
      confirmTip.value = "Loading...";

    });
}


const handleSearchDriver = (params) => {
  drivers.value = [];
  driverList({...params, status: '1', companyId: companyInfo.id}).then(res => {
    console.log("handleSearchDriver", res.records)
    drivers.value = res.records
    // bothSides.splice(0,bothSides.length,res.records);
  })
}

const selectDriver = (item) => {
  formData.driverBankCardNo = item.driverBankCardNo;
  formData.driverBankHolder = item.driverBankHolder;
  formData.driverBankName = item.driverBankName;
  formData.driverBankId = item.driverBankId;
  formData.driverUserId = item.driverUserId;
  formData.driverName = item.driverName;
  formData.driverPhone = item.driverPhone;
  formData.driverVehicleNo = item.driverVehicleNo;

}

const handleSearchBoth = (params) => {
  bothSides.value = [];
  list({...params, status: '1', companyId: companyInfo.id}).then(res => {
    console.log("handleSearchBoth", res.records)
    bothSides.value = res.records
    // bothSides.splice(0,bothSides.length,res.records);
  })
}
const selectConsigner = (item) => {
  formData.consignerName = item.name;
  formData.consignerPhone = item.phone;
  formData.consignerIdNum = item.idNum;
  formData.consignerAreaCode = item.areaCode;
  formData.consignerAreaName = item.areaName;
  formData.consignerDetailAddr = item.detailAddr;
  formData.consignerLnglat = item.lnglat;
}
const selectShipper = (item) => {
  formData.shipperName = item.name;
  formData.shipperPhone = item.phone;
  formData.shipperIdNum = item.idNum;
  formData.shipperAreaCode = item.areaCode;
  formData.shipperAreaName = item.areaName;
  formData.shipperDetailAddr = item.detailAddr;
  formData.shipperLnglat = item.lnglat;
}
/// ---
getCompanyInfo().then(res => {
  Object.assign(companyInfo, res)
})

</script>

<style lang="less" scoped>

</style>
